//@auther foolbread
//@time 2016-03-08
//@file ApnsHttp2/config/config.go

package config

import (
	"ApnsHttp2/log"
	"encoding/xml"
	"github.com/foolbread/fbcommon/config"
	"github.com/foolbread/fbcommon/golog"
	"io/ioutil"
	"os"
)

func InitConfig(path string) {
	golog.Info("initing ApnsHttp2 config...")
	g_config.cert = make(map[int]*CertificateInfo)

	c, err := config.LoadConfigByFile(path)
	if err != nil {
		golog.Critical(err)
	}

	var str string
	str = c.MustString("server", "listen_addr", "")
	golog.Info("listen_addr:", str)
	g_config.addr = str

	str = c.MustString("certificate", "cert_file", "")
	golog.Info("cert_file:", str)
	loadXmlConfig(str)

	str = c.MustString("log", "log_config", "")
	golog.Info("log_config:", str)
	log.SetLogPath(str)
}

func loadXmlConfig(file string) {
	f, err := os.Open(file)
	if err != nil {
		golog.Critical(err)
	}

	defer f.Close()
	content, err := ioutil.ReadAll(f)
	if err != nil {
		golog.Critical(err)
	}

	var infos certificateinfos
	err = xml.Unmarshal(content, &infos)
	if err != nil {
		golog.Critical(err)
	}

	for k, v := range infos.Infos {
		golog.Info("type:", v.Type, "name:", v.Name, "file:", v.FilePath, "password:", v.PassWord, "topic:",
			v.Topic, "certtype:", v.IsProduct, "connectcount:", v.Count)
		g_config.cert[v.Type] = &infos.Infos[k]
	}
}

func GetConfigInstance() *apnsConfig {
	return g_config
}

var g_config *apnsConfig = new(apnsConfig)

type certificateinfos struct {
	Infos []CertificateInfo `xml:"certificate"`
}

type CertificateInfo struct {
	Type      int    `xml:"type"`
	Name      string `xml:"name"`
	FilePath  string `xml:"p12file"`
	PassWord  string `xml:"password"`
	Topic     string `xml:"topic"`
	IsProduct bool   `xml:"product"`
	Count     int    `xml:"connectcount"`
}

type apnsConfig struct {
	cert    map[int]*CertificateInfo
	addr    string
	logpath string
}

func (c *apnsConfig) GetListenAddr() string {
	return c.addr
}

func (c *apnsConfig) GetCertificateInfos() map[int]*CertificateInfo {
	return c.cert
}

func (c *apnsConfig) GetLogFile() string {
	return c.logpath
}
